﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExpertMIS.Brokers;
using System.Collections;
using ExpertMIS.Entities;
using ExpertMIS.Forums.UserControl;
using ExpertMIS.Codes;
using System.Text;

namespace ExpertMIS.Forums
{
    public partial class QuestionForm : System.Web.UI.Page
    {
        private QuestionEntity _questionEntity = null;
        private DomainBroker _domainBroker = new DomainBroker();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request["oid"]))
            {
                Response.Redirect("~/Forums/QuestionRemoved.aspx", true);
                return;
            }

            LoadQuestion(Request["oid"]);
            LoadAnswer(Request["oid"]);
            if (!IsPostBack)
            {
                LoadExpertList(Request["oid"]);
            }

            ucPosterCard.CardClass = "smallCardTable";

            LoadRelatedDomainLastQuestions();
        }

        private void LoadRelatedDomainLastQuestions()
        {
            foreach (DomainEntity domain in _domainBroker.GetDomainsByQuerytionOID(_questionEntity.OID))
            {
                ucLastedQuestionList1.DomainOID = domain.OID;
                ucLastedQuestionList1.LoadAsDomainQuestion = true;
                break; // TODO, --> 仅仅显示该问题所属行业（领域）的第一个行业的最新问题！
            }
        }

        protected string GetQuestionContext()
        {
            if (_questionEntity != null)
                return _questionEntity.Context;
            else
                return "";
        }

        protected string LoginURL
        {
            get
            {
                string encodedUrl = HttpUtility.UrlEncode(ExpertMIS.Codes.Utility.GetWebRoot(this, "~/Forums/QuestionForm.aspx?oid=" + Request["oid"]));
                return ExpertMIS.Codes.Utility.GetWebRoot(this, "~/Login.aspx?requesturl=" + encodedUrl);
            }
        }

        protected bool UserLogon
        {
            get
            {
                return ExpertMIS.Codes.Utility.GetEnvironment().Logon;
            }
        }

        protected bool CanReply
        {
            get
            {
                return UserLogon &&
                    _questionEntity.Status != QuestionStatus.UnPassed &&
                    _questionEntity.Status != QuestionStatus.Accepted;
            }
        }

        protected bool CanAccept
        {
            get
            {
                return UserLogon &&
                    _questionEntity.Status == QuestionStatus.HasAnswer &&
                    !string.IsNullOrEmpty(_questionEntity.UserOID) &&
                    _questionEntity.UserOID.Equals(Utility.GetEnvironment().GetCurrentUser().OID);
            }
        }

        protected string GetOperationBar(bool answerZone)
        {
            StringBuilder sb = new StringBuilder();

            if (UserLogon)
            {
                if (CanReply && !_questionEntity.FAQ)
                {
                    if (sb.Length > 0) sb.Append(" | ");
                    sb.Append("<input type='button' onclick=\"scroll2anchor('answerForm',800);$('#txAnswer').focus();\" value=\"回答\"></input>");
                }

                if (CanAccept && answerZone && !_questionEntity.FAQ)
                {
                    if (sb.Length > 0) sb.Append(" | ");
                    sb.Append("<input type='button' href=\"#\" onclick=\"return doEvaluate();\" value=\"接受答案\"></input>");
                }
            }
            else if (!_questionEntity.FAQ && _questionEntity.Status != QuestionStatus.Accepted) 
            {
                if (sb.Length > 0) sb.Append(" | ");
                sb.Append(string.Format(
                    "<input type='button' onclick=\"window.location='../Login.aspx?requesturl={0}'\" value=\"登录后回答\"></input>",
                    HttpUtility.UrlEncode(ResolveUrl("~/Forums/QuestionForm.aspx?oid=" + _questionEntity.OID)))
                    );
            }

            if (sb.Length > 0) sb.Append(" | ");
            sb.Append("<a href=\"#qbody\" style=\"text-decoration: none; color: Black;\">TOP</a>");

            return sb.ToString();
        }

        private void LoadAnswer(string questionOID)
        {
            AnswerBroker broker = new AnswerBroker();

            dlAnswer.DataSource = broker.GetAnswerByQuestionOID(questionOID);
            dlAnswer.DataBind();
        }

        private void LoadExpertList(string questionOID)
        {
            AnswerBroker broker = new AnswerBroker();
            ADMUserBroker userBroker = new ADMUserBroker();
            List<ADMUserEntity> expertList = new List<ADMUserEntity>();

            IList<AnswerEntity> answers = broker.GetAnswerByQuestionOID(questionOID);
            foreach (AnswerEntity answer in answers)
            {
                ADMUserEntity user = userBroker.GetEntityByOID(answer.UserOID);
                if (user != null && user.IsExpert == true)
                {
                    expertList.Add(user);
                }
            }

            lblText.Visible = expertList.Count <= 0;
            dlExpertEvaluate.DataSource = expertList;
            dlExpertEvaluate.DataBind();
        }

        private void LoadQuestion(string oid)
        {
            QuestionBroker broker = new QuestionBroker();

            Hashtable htKeys = new Hashtable();
            htKeys.Add("OID", oid);
            _questionEntity = broker.GetEntity(htKeys) as QuestionEntity;

            if (_questionEntity == null)
            {
                Response.Redirect("~/Forums/QuestionRemoved.aspx", true);
                return;
            }

            ucPosterCard.LoadAsUser(_questionEntity.UserOID);
            lblTitle.Text = _questionEntity.Title;
            lblDate.Text = string.Format("{0}{1:yyyy-MM-dd}", _questionEntity.FAQ ? "发布时间：" : "提问时间：", _questionEntity.CreateDate);
            lblStatus.Text = string.Format("{0}", _questionEntity.FAQ ? "常见问题" : QuestionBroker.TranslateStatus(_questionEntity.Status));
        }

        protected void dlAnswer_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ucUserCard ucAnswerPoster = e.Item.FindControl("ucAnswerPoster") as ucUserCard;
                AnswerEntity answer = e.Item.DataItem as AnswerEntity;
                if (ucAnswerPoster != null && answer != null)
                {
                    ucAnswerPoster.CardClass = "smallCardTable";
                    ucAnswerPoster.LoadAsUser(answer.UserOID);
                }
            }
        }

        protected void btnEvaluate_Click(object sender, EventArgs e)
        {
            ExpertBroker expertBroker = new ExpertBroker();
            QuestionBroker questionBroker = new QuestionBroker();

            Dictionary<string, decimal> dictExpertGrades = new Dictionary<string, decimal>();

            foreach (DataListItem item in dlExpertEvaluate.Items)
            {
                DropDownList ddlEavluate = item.FindControl("ddlEavluate") as DropDownList;
                if (ddlEavluate != null)
                {
                    dictExpertGrades.Add(ddlEavluate.Attributes["expertoid"], Convert.ToDecimal(ddlEavluate.SelectedValue));
                }
            }

            questionBroker.UpdateQuestionStatue(_questionEntity.OID, QuestionStatus.Accepted);
            expertBroker.UpdateExpertTotalGrade(dictExpertGrades);

            LoadQuestion(_questionEntity.OID);
        }
    }
}
